package com.jml.反射;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class UserEntity {

	private String userName;

	private UserEntity() {
		System.out.println("对象初始化...");
	}


	private UserEntity(String userName) {
		System.out.println("userName:" + userName);
		this.userName = userName;
	}

	public static void main(String[] args)throws Exception{
		//第一种方式：
		Class<?> classc1  = Class.forName("com.jml.反射.UserEntity");
		UserEntity userEntity = (UserEntity)classc1.newInstance();
		userEntity.userName="反射Class.forName生成的类";
		System.out.println(userEntity.userName);
		//第二种方式：
		Class<?> Classc2 = UserEntity.class;
		UserEntity userEntity1 = (UserEntity)classc1.newInstance();
		userEntity1.userName="反射UserEntity.class生成的类";
		System.out.println(userEntity1.userName);
		//第三种方式：
		UserEntity userEntity3 = new UserEntity();
		Class<?> Classc3 = userEntity3.getClass(); //c3是运行时类 (e的运行时类是Employee)
		//获取类的所有方法
		Method[] declaredMethods = classc1.getMethods();
		for (int i = 0; i <declaredMethods.length ; i++) {
			Method declaredMethod = declaredMethods[i];
			String methodName = declaredMethod.getName();
			System.out.println(methodName);
		}
		//获取类的属性
		Field[] fields = classc1.getFields();
		for (int i = 0; i <fields.length ; i++) {
			Field field = fields[i];
			String methodName = field.getName();
			System.out.println(methodName);
		}
		Field[] declaredFields = classc1.getDeclaredFields();
		for (int i = 0; i <declaredFields.length ; i++) {
			Field field = declaredFields[i];
			String methodName = field.getName();
			System.out.println(methodName);
		}
		//根据参数类型获取构造函数,前提是构造函数是public而不是private
		Constructor<?> constructor = classc1.getConstructor(String.class);
		constructor.setAccessible(true);
		UserEntity userEntity2 = (UserEntity)constructor.newInstance("String 构造函数");
		System.out.println(userEntity2.userName);
	}

}
